const path = require('path');

const { fileUploadFail, systemError, invalidGoods } = require('../constant/status.type');

const { createGoods, updateGoods, removeGoods } = require('../service/goods.service');

class GoodsController {
  async upload(ctx) {
    try {
      const { file } = ctx.request.files;
      if (file) {
        if (file.mimetype !== 'image/jpeg' && file.mimetype !== 'image/png') {
          return ctx.app.emit('error', fileUploadFail, ctx);
        }
        ctx.body = {
          code: 0,
          message: '上传成功',
          result: {
            fileUrl: 'http://localhost:15432/' + path.basename(file.newFilename)
          }
        }
      } else {
        return ctx.app.emit('error', fileUploadFail, ctx);
      }

    } catch (error) {
      console.log(error);
    }
  }

  async create(ctx) {
    try {
      //service层处理
      const res = await createGoods(ctx.request.body);
      ctx.body = {
        code: 0,
        message: '发布商品成功',
        result: res
      }
    } catch (error) {
      console.error(error);
      return ctx.app.emit('error', systemError, ctx);
    }
  }

  async update(ctx) {
    try {
      const res = await updateGoods(ctx.request.body);
      if (res) {
        ctx.body = {
          code: 0,
          message: '更新商品成功',
          result: ''
        }
      } else {
        return ctx.app.emit('error', invalidGoods, ctx);
      }
    } catch (error) {
      console.error(error);
    }
  }

  async remove(ctx) {
    try {
      console.log('--------------', ctx.params.id);
      await removeGoods(ctx.params.id);
      ctx.body = {
        code: 0,
        message: '删除商品成功',
        result: ''
      }
    } catch (error) {
      console.error(error);
    }
  }
}

module.exports = new GoodsController();